package com.foreveredu.propms.web.struts.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.foreveredu.propms.domain.StrongNews;
import com.foreveredu.propms.domain.PageModel;
import com.foreveredu.propms.service.IManagementService;
import com.foreveredu.propms.web.struts.actionform.StrongNewsActionForm;

public class StrongNewsAdminAction extends AbstractBaseDispatchAction {

	private IManagementService managementService = null;
	
	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}

	public ActionForward toAdd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("toAdd");
	}
	
	@SuppressWarnings("unchecked")
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		StrongNewsActionForm StrongNewsform = (StrongNewsActionForm)form;
		StrongNews StrongNews = new StrongNews();
		StrongNewsform.setNewscontent(StrongNewsform.getFckContent());
		PropertyUtils.copyProperties(StrongNews, StrongNewsform);
		// 添加新闻的表单校验
		if (StrongNewsform.getNewstopic() == null
				|| "".equals(StrongNewsform.getNewstopic())) {
			request.setAttribute("StrongNews", StrongNews);
			request.setAttribute("StrongNewsTopicError", "请输入动态标题！");
			return mapping.findForward("toAdd");
		}
		if (StrongNewsform.getFckContent() == null
				|| "".equals(StrongNewsform.getFckContent())) {
			request.setAttribute("StrongNews", StrongNews);
			request.setAttribute("StrongNewsContentError", "请输入动态内容！");
			return mapping.findForward("toAdd");
		}
		if (StrongNewsform.getBelong() == 0) {
			request.setAttribute("StrongNews", StrongNews);
			request.setAttribute("StrongNewsBelongError", "请选择动态属性！");
			return mapping.findForward("toAdd");
		}

		// 获取文件并存储
		String photo = null;
		
		// 将考生上传照片保存到photo文件夹中
		String dirPath = request.getSession().getServletContext().getRealPath("/companyPhoto");

		// 判断路径是否存在，如果不存在，就创建这个路径
		File fileDir = new File(dirPath);
			if (!fileDir.exists()) {
				fileDir.mkdir();
			}
			
		Hashtable<Object, Object> files = form.getMultipartRequestHandler()
				.getFileElements();
		for (Enumeration<Object> e = files.keys(); e.hasMoreElements();) {
			String key = (String) e.nextElement();

			try {
				FormFile formFile = (FormFile) files.get(key);
				String fileName = formFile.getFileName().trim();// 获得待上传的文件名

				if (fileName == null || fileName.equals("")) {
					request.setAttribute("imageEmptyError", "请按要求上传照片！");
					return mapping.findForward("toAdd");
				}
				
				// 获得当天日期
				 Date date = new Date();
				 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				 String datetime = sdf.format(date);
				
				// 保存后的文件名不能使用原来的,可以防止下载出错,使用日期+随机数

				String newFileName = datetime;
				
				 Random rnd = new Random();
				 for (int i = 0; i < 10; i++) {
				 newFileName += rnd.nextInt(10);
				 };

				// 读出原文件的扩展名
				String ext = "";
				int pos = fileName.lastIndexOf(".");
				ext = fileName.substring(pos);// 得到扩展名

//						if (!ext.equalsIgnoreCase(".jpg")) {
//							request.setAttribute("imgFormatError", "照片格式不对，只能是jpg格式！");
//							return mapping.findForward("toEnroll");
//						}

				// 拼出完整的新文件名
				newFileName = newFileName + ext;
				photo = newFileName;

				InputStream is = formFile.getInputStream();
				OutputStream os = new FileOutputStream(dirPath
						+ File.separatorChar + newFileName);

				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				while ((bytesRead = is.read(buffer)) != -1) {
					os.write(buffer, 0, bytesRead);
				}
				os.flush();

				is.close();
				os.close();

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		
		StrongNews.setShowphoto(photo);
		
		SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
		StrongNews.setNewstime(time.format(new Date()));
		StrongNews.setUpdatetime(time.format(new Date()));
		
		managementService.saveStrongNews(StrongNews);
		
		if (StrongNewsform.getBelong() == 1) {
			return mapping.findForward("xqxxAdminList");
		}
		if (StrongNewsform.getBelong() == 2) {
			return mapping.findForward("tthdAdminList");
		}

		return null;
	}

	// 通过ID查找StrongNews详情
	public ActionForward findStrongNewsById(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		StrongNewsActionForm StrongNewsform = (StrongNewsActionForm) form;
		StrongNews StrongNews = managementService.findStrongNewsById(StrongNewsform.getId());
		request.setAttribute("strongNews", StrongNews);
		StrongNews.setTotal(StrongNews.getTotal() + 1);
		managementService.updateStrongNews(StrongNews);
		return mapping.findForward("findStrongNewsById");
	}

	public ActionForward findStrongNewsByBelong(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		StrongNewsActionForm StrongNewsform = (StrongNewsActionForm) form;
		StrongNews StrongNews = managementService.findStrongNewsByBelong(StrongNewsform.getBelong());
		request.setAttribute("strongNews", StrongNews);
		managementService.updateStrongNews(StrongNews);
		return mapping.findForward("toUpdateStrongNews");
	}

	// StrongNews 翻页列表
	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		StrongNewsActionForm StrongNewsform = (StrongNewsActionForm) form;
		int offset = 0;
		String pageOffset = request.getParameter("pager.offset");// 获得翻页参数，即下一开始的纪录位置
		if (pageOffset != null && !pageOffset.equals("")) {
			offset = Integer.parseInt(pageOffset);
		}
		if (offset < 0) {
			return mapping.findForward("StrongNewsList");
		}
		PageModel pm = managementService.findStrongNewsList(offset,
				StrongNewsform.getBelong());
		request.setAttribute("pm", pm);
		if (StrongNewsform.getBelong() == 1) {
			return mapping.findForward("xqxxList");
		}
		if (StrongNewsform.getBelong() == 2) {
			return mapping.findForward("tthdList");
		}
		return null;
	}

	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		StrongNewsActionForm StrongNewsform = (StrongNewsActionForm) form;
		managementService.deleteStrongNewsById(StrongNewsform.getId());

		if (StrongNewsform.getBelong() == 1) {
			return mapping.findForward("xqxxAdminList");
		}
		if (StrongNewsform.getBelong() == 2) {
			return mapping.findForward("tthdAdminList");
		}
		return null;
	}

	public ActionForward toUpdateStrongNews(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		StrongNewsActionForm StrongNewsform = (StrongNewsActionForm) form;
		StrongNews StrongNews = managementService.findStrongNewsById(StrongNewsform.getId());
		request.setAttribute("strongNews", StrongNews);
		return mapping.findForward("toUpdateStrongNews");
	}
	
	@SuppressWarnings("unchecked")
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		StrongNewsActionForm StrongNewsform = (StrongNewsActionForm) form;
		StrongNews StrongNews = managementService.findStrongNewsById(StrongNewsform.getId());
		if (StrongNewsform.getNewstopic() == null
				|| "".equals(StrongNewsform.getNewstopic())) {
			request.setAttribute("strongNews", StrongNews);
			request.setAttribute("StrongNewsTopicError", "请输入动态标题！");
			return mapping.findForward("toUpdateStrongNews");
		}
		if (StrongNewsform.getFckContent() == null
				|| "".equals(StrongNewsform.getFckContent())) {
			request.setAttribute("strongNews", StrongNews);
			request.setAttribute("StrongNewsContentError", "请输入动态内容！");
			return mapping.findForward("toUpdateStrongNews");
		}
		if (StrongNewsform.getBelong() == 0) {
			request.setAttribute("strongNews", StrongNews);
			request.setAttribute("StrongNewsBelongError", "请选择动态属性！");
			return mapping.findForward("toUpdateStrongNews");
		}
		
		// 获取文件并存储
		String photo = null;
		
		// 将考生上传照片保存到photo文件夹中
		String dirPath = request.getSession().getServletContext().getRealPath("/companyPhoto");

		// 判断路径是否存在，如果不存在，就创建这个路径
		File fileDir = new File(dirPath);
			if (!fileDir.exists()) {
				fileDir.mkdir();
			}
			
		
		Hashtable<Object, Object> files = form.getMultipartRequestHandler()
				.getFileElements();
		for (Enumeration<Object> e = files.keys(); e.hasMoreElements();) {
			String key = (String) e.nextElement();

			try {
				FormFile formFile = (FormFile) files.get(key);
				String fileName = formFile.getFileName().trim();// 获得待上传的文件名
				
				if(fileName != null && !"".equals(fileName)){
					//删除原相片	
					File file = new File(dirPath+File.separator+StrongNews.getShowphoto());
					if (file != null) {
						file.delete();
					}
				// 获得当天日期
				 Date date = new Date();
				 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				 String datetime = sdf.format(date);
				
				// 保存后的文件名不能使用原来的,可以防止下载出错,使用日期+随机数

				String newFileName = datetime;
				
				 Random rnd = new Random();
				 for (int i = 0; i < 10; i++) {
				 newFileName += rnd.nextInt(10);
				 };

				// 读出原文件的扩展名
				String ext = "";
				int pos = fileName.lastIndexOf(".");
				ext = fileName.substring(pos);// 得到扩展名

//								if (!ext.equalsIgnoreCase(".jpg")) {
//									request.setAttribute("imgFormatError", "照片格式不对，只能是jpg格式！");
//									return mapping.findForward("toEnroll");
//								}

				// 拼出完整的新文件名
				newFileName = newFileName + ext;
				photo = newFileName;

				InputStream is = formFile.getInputStream();
				OutputStream os = new FileOutputStream(dirPath
						+ File.separatorChar + newFileName);

				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				while ((bytesRead = is.read(buffer)) != -1) {
					os.write(buffer, 0, bytesRead);
				}
				os.flush();

				is.close();
				os.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			}
		
		if(photo != null && !"".equals(photo)){
			StrongNews.setShowphoto(photo);
		}
		
		StrongNews.setNewstopic(StrongNewsform.getNewstopic());
		StrongNews.setBelong(StrongNewsform.getBelong());
		StrongNews.setNewscontent(StrongNewsform.getFckContent());

		SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
		StrongNews.setUpdatetime(time.format(new Date()));

		managementService.updateStrongNews(StrongNews);

		if (StrongNewsform.getBelong() == 1) {
			return mapping.findForward("xqxxAdminList");
		}
		if (StrongNewsform.getBelong() == 2) {
			return mapping.findForward("tthdAdminList");
		}
		return null;
	}
}
